from django.db import models
from django.contrib.auth import get_user_model
from apps.books.models import Book

User = get_user_model()


class SiteVisit(models.Model):
    """网站访问统计"""
    date = models.DateField(unique=True, verbose_name='日期')
    total_visits = models.IntegerField(default=0, verbose_name='总访问量')
    unique_visitors = models.IntegerField(default=0, verbose_name='独立访客数')
    page_views = models.IntegerField(default=0, verbose_name='页面浏览量')
    bounce_rate = models.FloatField(default=0.0, verbose_name='跳出率')
    avg_session_duration = models.IntegerField(default=0, verbose_name='平均会话时长(秒)')
    
    # 设备统计
    desktop_visits = models.IntegerField(default=0, verbose_name='桌面端访问')
    mobile_visits = models.IntegerField(default=0, verbose_name='移动端访问')
    tablet_visits = models.IntegerField(default=0, verbose_name='平板访问')
    
    # 来源统计
    direct_visits = models.IntegerField(default=0, verbose_name='直接访问')
    search_visits = models.IntegerField(default=0, verbose_name='搜索引擎')
    social_visits = models.IntegerField(default=0, verbose_name='社交媒体')
    referral_visits = models.IntegerField(default=0, verbose_name='外部链接')
    
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = 'site_visits'
        verbose_name = '网站访问统计'
        verbose_name_plural = '网站访问统计'
        ordering = ['-date']

    def __str__(self):
        return f"{self.date} 访问统计"


class BookView(models.Model):
    """图书浏览统计"""
    book = models.ForeignKey(Book, on_delete=models.CASCADE, related_name='view_stats')
    date = models.DateField(verbose_name='日期')
    view_count = models.IntegerField(default=0, verbose_name='浏览次数')
    unique_visitors = models.IntegerField(default=0, verbose_name='独立访客数')
    
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = 'book_views'
        verbose_name = '图书浏览统计'
        verbose_name_plural = '图书浏览统计'
        unique_together = ['book', 'date']
        ordering = ['-date']

    def __str__(self):
        return f"{self.book.title} - {self.date}"


class SalesAnalytics(models.Model):
    """销售分析"""
    date = models.DateField(verbose_name='日期')
    total_orders = models.IntegerField(default=0, verbose_name='订单总数')
    total_amount = models.DecimalField(max_digits=10, decimal_places=2, default=0, verbose_name='销售总额')
    total_items = models.IntegerField(default=0, verbose_name='销售商品总数')
    
    # 用户统计
    new_users = models.IntegerField(default=0, verbose_name='新增用户数')
    active_users = models.IntegerField(default=0, verbose_name='活跃用户数')
    returning_users = models.IntegerField(default=0, verbose_name='回访用户数')
    
    # 订单统计
    completed_orders = models.IntegerField(default=0, verbose_name='已完成订单')
    cancelled_orders = models.IntegerField(default=0, verbose_name='已取消订单')
    refund_orders = models.IntegerField(default=0, verbose_name='退款订单')
    
    # 商品统计
    top_selling_books = models.JSONField(default=list, verbose_name='热销图书')
    low_stock_books = models.JSONField(default=list, verbose_name='低库存图书')
    
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = 'sales_analytics'
        verbose_name = '销售分析'
        verbose_name_plural = '销售分析'
        unique_together = ['date']
        ordering = ['-date']

    def __str__(self):
        return f"{self.date} 销售分析"


class UserRetention(models.Model):
    """用户留存分析"""
    date = models.DateField(verbose_name='日期')
    
    # 新增用户留存
    new_users = models.IntegerField(default=0, verbose_name='新增用户数')
    day1_retention = models.FloatField(default=0.0, verbose_name='次日留存率')
    day7_retention = models.FloatField(default=0.0, verbose_name='7日留存率')
    day30_retention = models.FloatField(default=0.0, verbose_name='30日留存率')
    
    # 活跃用户留存
    active_users = models.IntegerField(default=0, verbose_name='活跃用户数')
    weekly_active_users = models.IntegerField(default=0, verbose_name='周活跃用户数')
    monthly_active_users = models.IntegerField(default=0, verbose_name='月活跃用户数')
    
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = 'user_retention'
        verbose_name = '用户留存分析'
        verbose_name_plural = '用户留存分析'
        unique_together = ['date']
        ordering = ['-date']

    def __str__(self):
        return f"{self.date} 用户留存分析"


class HeatmapData(models.Model):
    """热力图数据"""
    page_name = models.CharField(max_length=100, verbose_name='页面名称')
    element_id = models.CharField(max_length=100, verbose_name='元素ID')
    element_type = models.CharField(max_length=50, verbose_name='元素类型')
    x_coordinate = models.IntegerField(verbose_name='X坐标')
    y_coordinate = models.IntegerField(verbose_name='Y坐标')
    click_count = models.IntegerField(default=0, verbose_name='点击次数')
    hover_count = models.IntegerField(default=0, verbose_name='悬停次数')
    date = models.DateField(verbose_name='日期')
    
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = 'heatmap_data'
        verbose_name = '热力图数据'
        verbose_name_plural = '热力图数据'
        ordering = ['-date', '-click_count']

    def __str__(self):
        return f"{self.page_name} - {self.element_id}"


class SearchKeyword(models.Model):
    """搜索关键词统计"""
    keyword = models.CharField(max_length=100, verbose_name='关键词')
    search_count = models.IntegerField(default=0, verbose_name='搜索次数')
    result_count = models.IntegerField(default=0, verbose_name='结果数量')
    click_count = models.IntegerField(default=0, verbose_name='点击次数')
    conversion_rate = models.FloatField(default=0.0, verbose_name='转化率')
    date = models.DateField(verbose_name='日期')
    
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = 'search_keywords'
        verbose_name = '搜索关键词'
        verbose_name_plural = '搜索关键词'
        unique_together = ['keyword', 'date']
        ordering = ['-date', '-search_count']

    def __str__(self):
        return f"{self.keyword} - {self.date}"


class RealTimeAlert(models.Model):
    """实时警报"""
    ALERT_TYPE_CHOICES = [
        ('high_traffic', '高流量'),
        ('low_stock', '低库存'),
        ('system_error', '系统错误'),
        ('security', '安全警报'),
        ('performance', '性能警报'),
    ]

    SEVERITY_CHOICES = [
        ('low', '低'),
        ('medium', '中'),
        ('high', '高'),
        ('critical', '严重'),
    ]

    alert_type = models.CharField(max_length=20, choices=ALERT_TYPE_CHOICES, verbose_name='警报类型')
    severity = models.CharField(max_length=20, choices=SEVERITY_CHOICES, verbose_name='严重程度')
    title = models.CharField(max_length=200, verbose_name='警报标题')
    message = models.TextField(verbose_name='警报内容')
    data = models.JSONField(default=dict, verbose_name='相关数据')
    
    # 处理状态
    is_read = models.BooleanField(default=False, verbose_name='是否已读')
    is_resolved = models.BooleanField(default=False, verbose_name='是否已解决')
    resolved_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, related_name='resolved_alerts')
    resolved_at = models.DateTimeField(null=True, blank=True, verbose_name='解决时间')
    resolution_note = models.TextField(blank=True, verbose_name='解决备注')
    
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = 'real_time_alerts'
        verbose_name = '实时警报'
        verbose_name_plural = '实时警报'
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.title} - {self.severity}"
